package com.ebt.m.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.account.AccountHttps;
import com.ebt.m.account.json.AccountResponse;
import com.ebt.m.account.json.ValidateCodeCheckResponse;
import com.ebt.m.account.json.ValidateCodeSendResponse;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.event.LoginEvent;
import com.ebt.m.jpush.JPushUtil;
import com.ebt.m.utils.CountDownManager;
import com.ebt.m.utils.CountDownManager.CountDownListener;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.android.EBTUserInfoHelper;
import com.ebt.m.commons.utils.NetUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ChangePasswordActivity extends BaseToolBarActivity {

    @BindView(R.id.view_count_down)
    View view_count_down;
    @BindView(R.id.view_step0)
    View view_step0;
    @BindView(R.id.view_step1)
    View view_step1;
    @BindView(R.id.button_step0)
    Button button_step0;
    @BindView(R.id.button_step1)
    Button button_step1;
    @BindView(R.id.text_view_vcode_hint)
    TextView text_view_vcode_hint;
    @BindView(R.id.text_view_title_hint)
    TextView text_view_title_hint;

    @BindView(R.id.edit_text_vc)
    EditText edit_text_vc;
    @BindView(R.id.edit_text_0)
    EditText edit_text_0;
    @BindView(R.id.edit_text_1)
    EditText edit_text_1;
    @BindView(R.id.delete_0)
    ImageView delete_0;
    @BindView(R.id.delete_1)
    ImageView delete_1;

    private ProgressDialog mProgressDialog;

    private static String mValidateId;
    private boolean mHasSend = false;

    private CountDownListener mCountDownListener;
    private CountDownManager mCountDownManager;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);
        mCountDownManager = CountDownManager.getInstance();
        ButterKnife.bind(this);
        initProgressDialog();
        initView();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (mCountDownManager.isCountingDown()) {
            initVCodeHintForCountingDown();
            return;
        }
        sendVCodeRequest();
    }

    public void initView() {
        setTitle("修改密码");
        //STEP 0
        view_step0.setVisibility(View.VISIBLE);
        view_step1.setVisibility(View.GONE);
        mCountDownListener = new CountDownListener() {
            @Override
            public void onTick(long remainMillisSecond) {
                int countdownSecond = (int) (remainMillisSecond / 1000);
                updateVCodeHint(mHasSend, String.valueOf(countdownSecond));
            }

            @Override
            public void onFinish() {
                updateVCodeHint(mHasSend, "");
            }
        };
        mCountDownManager.setCountDownListener(mCountDownListener);

        edit_text_vc.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void afterTextChanged(Editable editable) {
                onTextChangeVC(editable.toString());
            }
        });
        updateButtonStep0State(edit_text_vc.getText().toString().trim(), mValidateId);

        //STEP1
        edit_text_0.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void afterTextChanged(Editable editable) {
                onTextChange0(editable.toString());
            }
        });
        edit_text_1.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void afterTextChanged(Editable editable) {
                onTextChange1(editable.toString());
            }
        });
        updateStep1Button();
    }

    private void initVCodeHintForCountingDown() {
        text_view_vcode_hint.setText("重新发送");
        text_view_vcode_hint.setTextColor(getResources().getColor(R.color.btn_green_disable));
    }

    private void updateVCodeHint(boolean hasSend, String countDownHint) {
        if (TextUtils.isEmpty(countDownHint)) {
            text_view_vcode_hint.setText("重新发送");
            text_view_vcode_hint.setTextColor(getResources().getColor(R.color.btn_green_normal));
        } else {
            text_view_vcode_hint.setText("重新发送(" + countDownHint + ")");
            text_view_vcode_hint.setTextColor(getResources().getColor(R.color.btn_green_disable));
        }
    }

    private void updateTitleHintView(String phoneNumber) {
        //已向手机号 100000000 发送短信验证码
        String str1 = "已向手机号 ";
        String str2 = " 发送短信验证码";
        SpannableString spannableString = new SpannableString(str1 + phoneNumber + str2);

        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#666666"));
        RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);

        spannableString.setSpan(colorSpan, str1.length(), str1.length() + phoneNumber.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(sizeSpan, str1.length(), str1.length() + phoneNumber.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        text_view_title_hint.setText(spannableString);
    }

    private void onTextChangeVC(String s) {
        updateButtonStep0State(s, mValidateId);
    }

    private void updateButtonStep0State(String vCode, String validateId) {
        if (TextUtils.isEmpty(vCode)) {
            button_step0.setEnabled(false);
        } else {
//            if (TextUtils.isEmpty(validateId)){
//                button_step0.setEnabled(false);
//            }else{
            button_step0.setEnabled(true);
//            }
        }
    }

    private void onTextChange0(String s) {
        if (TextUtils.isEmpty(s)) {
            delete_0.setVisibility(View.GONE);
        } else {
            delete_0.setVisibility(View.VISIBLE);
        }
        updateStep1Button();
    }

    private void onTextChange1(String s) {
        if (TextUtils.isEmpty(s)) {
            delete_1.setVisibility(View.GONE);
        } else {
            delete_1.setVisibility(View.VISIBLE);
        }
        updateStep1Button();
    }

    private void updateStep1Button() {

        if (!TextUtils.isEmpty(edit_text_0.getText().toString().trim()) && !TextUtils.isEmpty(edit_text_1.getText().toString().trim())) {
            button_step1.setBackgroundResource(R.drawable.selector_button_green_account_a);
        } else {
            button_step1.setBackgroundResource(R.drawable.selector_button_green_account_b);
        }

        /*if (edit_text_0.getText().toString().equals(edit_text_1.getText().toString())) {
            //检查密码是否符合格式需求
            if (edit_text_0.getText().toString().length() >= 8) {
                button_step1.setBackgroundResource(R.drawable.selector_button_green_account_a);
                return;
            }
        }
        button_step1.setBackgroundResource(R.drawable.selector_button_green_account_b);*/
//        button_step1.setEnabled(false);
    }

    @OnClick(R.id.button_step0)
    public void onStep0ButtonClicked() {
        //校对验证码
        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast(getString(R.string.network_fail));
            return;
        }

        if (TextUtils.isEmpty(mValidateId)) {
            ToastUtil.showToast("验证码无效，请重新获取");
            return;
        }

        //发送验证码
        AccountHttps.getInstance().checkValidateCode(
                AppContext.getCurrentUser().getPhone(),
                mValidateId,
                edit_text_vc.getText().toString().trim(),
                getCheckVCodeSubscriber());

    }

    @OnClick(R.id.view_count_down)
    public void onGetVCodeClicked() {
        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast(getString(R.string.network_fail));
            return;
        }
        if (mCountDownManager.isCountingDown()) {
            ToastUtil.showToast("请稍后再发送验证码");
            return;
        }
        sendVCodeRequest();
    }

    private void sendVCodeRequest() {
        //没有手机号，无法接收验证码短信
        if (TextUtils.isEmpty(AppContext.getCurrentUser().getPhone())) {
            ToastUtil.showToastL("请先绑定手机");
            return;
        }
        showProgress("正在获取验证码...");
        mCountDownManager.startCountDown();
        mHasSend = true;
        //发送验证码
        AccountHttps.getInstance().sendValidateCode(
                AppContext.getCurrentUser().getPhone(),
                getSendVCodeSubscriber(), this);
    }

    @OnClick(R.id.button_step1)
    public void onChangePasswordClicked() {
        if (!edit_text_0.getText().toString().trim().equals(edit_text_1.getText().toString().trim())) {
            ToastUtil.showToastL(getString(R.string.password_equal_fail));
            return;
        }

        if (!DataValidation.checkPasswordValidate(edit_text_0.getText().toString().trim())) {
            ToastUtil.showToastL(getString(R.string.password_format_fail));
            return;
        }

        if (!NetUtils.isNetworkAvailable(this)) {
            ToastUtil.showToast(getString(R.string.network_fail));
            return;
        }
        showProgress("正在更改密码...");
        setViewStep1Enable(false);
        //使用reset接口
        AccountHttps.getInstance().resetAccountPassword(
                AppContext.getCurrentUser().getPhone(),
                edit_text_0.getText().toString().trim(),
                getChangePasswordSubscriber());
    }

    private void setViewStep1Enable(boolean b) {
//        button_step1.setEnabled(b);
        if (b) {
            button_step1.setBackgroundResource(R.drawable.selector_button_green_account_a);
        } else {
            button_step1.setBackgroundResource(R.drawable.selector_button_green_account_b);
        }

        edit_text_0.setEnabled(b);
        edit_text_1.setEnabled(b);
    }

    //发送验证码
    private Observer getSendVCodeSubscriber() {
        return new Observer<BaseDataResult<ValidateCodeSendResponse>>() {
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtils.checkHttpException(ChangePasswordActivity.this, e);
                hideProgress();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<ValidateCodeSendResponse> responseJson) {
                hideProgress();
                if (responseJson == null || responseJson.getData() == null) {
                    ToastUtil.showSendVCodeErrorMessage(responseJson);
                    return;
                }
                if (responseJson.getData() != null) {
                    ValidateCodeSendResponse validateCodeSendResponse = responseJson.getData();
                    if (validateCodeSendResponse.isSuccess) {
                        mValidateId = validateCodeSendResponse.getValidateId();
                        updateTitleHintView(AppContext.getCurrentUser().getPhone());
                    } else {
                        ToastUtil.showSendVCodeErrorMessage(responseJson);
                    }
                }
            }
        };
    }

    //校对验证码
    private Observer getCheckVCodeSubscriber() {
        return new Observer<BaseDataResult<ValidateCodeCheckResponse>>() {
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showCheckVCodeErrorMessage(null);
                hideProgress();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<ValidateCodeCheckResponse> responseJson) {
                hideProgress();
                if (responseJson == null || responseJson.getData() == null) {
                    ToastUtil.showCheckVCodeErrorMessage(responseJson);
                    return;
                }
                if (responseJson.getData() != null) {
                    ValidateCodeCheckResponse validateCodeCheckResponse = responseJson.getData();
                    if (validateCodeCheckResponse.isSuccess) {
                        //验证成功
                        view_step0.setVisibility(View.GONE);
                        view_step1.setVisibility(View.VISIBLE);
                    } else {
                        //验证失败，显示错误信息
                        ToastUtil.showCheckVCodeErrorMessage(responseJson);
                    }
                }
            }
        };
    }

    //更改密码
    private Observer getChangePasswordSubscriber() {
        return new Observer<BaseDataResult<AccountResponse>>() {
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast(getString(R.string.change_password_error));
                hideProgress();
                setViewStep1Enable(true);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<AccountResponse> responseJson) {
                hideProgress();
                setViewStep1Enable(true);
                if (responseJson == null || responseJson.getData() == null) {
                    ToastUtil.showToast(getString(R.string.change_password_error));
                    return;
                }
                if (responseJson.getData() != null) {
                    AccountResponse changePassword = responseJson.getData();
                    if (changePassword.isSuccess) {
                        //密码修改成功，需要重新登录
                        ToastUtil.showToastL("修改密码成功");

                        AppInitService.getEbtApi()
                                .userLoginOut()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(response -> loginOutAction(), throwable -> loginOutAction());

                    } else {
                        //密码修改失败
                        ToastUtil.showToastDL("修改密码失败");
                    }
                }
            }
        };
    }

    private void loginOutAction() {
        String userName = AppContext.getCurrentUser().getPhone();
        AppContext.clearLoginInfo(this);
        EventBus.getDefault().post(new LoginEvent(false));
        //退出登录
        Intent intent = new Intent(ChangePasswordActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setAction(LoginActivity.ACTION_FROM_RESETPWD);
        intent.putExtra(LoginActivity.USERNAME_KEY, userName);
        startActivity(intent);
        mValidateId = "";
    }

    @OnClick(R.id.delete_0)
    public void onDelete0Clicked() {
        edit_text_0.setText("");
    }

    @OnClick(R.id.delete_1)
    public void onDelete1Clicked() {
        edit_text_1.setText("");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginEvent event) {
        if (event == null) {
            return;
        }
        if (!event.login) {
            this.finish();
        }
    }

    private void initProgressDialog() {
        mProgressDialog = new ProgressDialog(ChangePasswordActivity.this, R.style.LightDialog);
        mProgressDialog.setIndeterminate(true);
    }

    private void showProgress(String message) {
        if (mProgressDialog != null && !mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(message);
            mProgressDialog.show();
        }
    }

    private void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}
